package com.ruoyi.controller;

import com.ruoyi.service.impl.WeChatPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/wechatApp/pay")
public class WeChatPayController {

    @Autowired
    private WeChatPayService weChatPayService;

    // 获取支付参数
    @PostMapping("/getWxPayParams")
    public ResponseEntity<?> getWxPayParams(@RequestBody Map<String, String> data) {
        try {
            String orderId = data.get("orderId");
            String totalFee = data.get("total_fee");
            String openid = data.get("openid");
            String body = data.get("body");
            System.out.println("orderId: " + orderId);
            System.out.println("totalFee: " + totalFee);
            System.out.println("openid: " + openid);
            System.out.println("body: " + body);
            Map<String, String> orderResult = weChatPayService.createOrder(orderId, totalFee, openid, body);
            String prepayId = orderResult.get("prepay_id");
            System.out.println("prepayId: " + prepayId);
            if (prepayId != null) {
                Map<String, String> payParams = weChatPayService.getPayParams(prepayId);
                return ResponseEntity.ok(payParams);
            } else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("生成预支付订单失败");
            }
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器异常");
        }
    }

    // 支付结果通知
    @PostMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) throws IOException {
        weChatPayService.handlePaymentNotification(request, response);
    }
}